import { createWriteStream } from 'fs';
import axios from 'axios';
import { Log, ILoggable } from '../utils/Log';

/**
 * File Service
 */
export class FileService implements ILoggable {
    public readonly DOMAIN = 'meminsight';
    public readonly TAG = FileService.name;
    private static _instance: FileService;
    private constructor() {}

    /**
     * FileService instance
     * @returns FileService instance
     */
    public static instance(): FileService {
        if (!FileService._instance) {
            FileService._instance = new FileService();
        }
        return FileService._instance;
    }

    /**
     * 
     * @param url file url
     * @param filepath filepath
     * @returns 
     */
    public async download(url: string, filepath: string): Promise<void> { 
        const response = await axios({
            url,
            method: 'GET',
            responseType: 'stream'
        });
        const fileWriter = createWriteStream(filepath);
        response.data.pipe(fileWriter);
        return new Promise((resolve, reject) => {
            fileWriter.on('finish', () => {
                Log.infoX(this, `File ${url} downloaded to ${filepath} successfully`);
                resolve();
            });
            fileWriter.on('error', (err) => {
                Log.errorX(this, `Failed to download file ${url}, Status code: ${err}`);
                reject(err);
            });
        });
    }
}